package com.woniuxy.cloud.carl.carlgoods.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.woniuxy.cloud.carl.carlgoods.app.util.OSSUtil;
import com.woniuxy.cloud.carl.carlgoods.client.SkuMannagerClient;
import com.woniuxy.cloud.carl.carlgoods.client.param.AddSkuParam;
import com.woniuxy.cloud.carl.carlgoods.client.param.ModifySkuParam;
import com.woniuxy.cloud.carl.carlgoods.common.CarlgoodsResultCode;
import com.woniuxy.cloud.carl.carlgoods.common.ConstData;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.PropValueMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SkuMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SpuMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.model.PropValue;
import com.woniuxy.cloud.carl.carlgoods.infra.model.Sku;
import com.woniuxy.cloud.carl.carlgoods.infra.model.Spu;
import com.woniuxy.cloud.carl.carlgoods.service.SkuService;
import com.woniuxy.cloud.carl.store.client.StoreClient;
import com.woniuxy.cloud.carl.store.client.param.GetStoreParam;
import com.woniuxy.cloud.carl.store.client.result.StoreDto;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@CrossOrigin("*")
public class SkuMannagerImpl implements SkuMannagerClient {
@Resource
    private PropValueMapper propValueMapper;
    @Resource
private SpuMapper spuMapper;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private SkuService skuService;
@Resource
private StoreClient storeClient;

    @Autowired
    private OSSUtil ossUtil;

    @Override
    public Result addsku(AddSkuParam param) {
        Spu spu = spuMapper.selectById(param.getSpuId());
        Assert.state(spu!=null,"不存在该种类型的商品");

        GetStoreParam getStoreParam = new GetStoreParam();
        getStoreParam.setStoreId(param.getStoreId());
        Result<List<StoreDto>> r = storeClient.getStore(getStoreParam);
        List<StoreDto> storeDtos = r.getData();
        if(storeDtos==null||storeDtos.size()==0){
            throw new MallException(CarlgoodsResultCode.STORE_NOT_EXIST);
        }

        Sku sku = BeanUtil.toBean(param, Sku.class);
        String quicklySearch = param.getQuicklySearch();
        String[] intpropvalueIds = quicklySearch.split("-");
        List<String> strlist = Arrays.asList(intpropvalueIds);
        List<Long> longs = new ArrayList<>();
        strlist.forEach(o->longs.add(Long.valueOf(o)));
        Long propvalueId1 = longs.get(0);//获得第一个属性值id
        Long propvalueId2 = longs.get(1);//获得第二个属性值id
        PropValue propValue1 = propValueMapper.selectById(propvalueId1);
        PropValue propValue2 = propValueMapper.selectById(propvalueId2);
        Assert.state(propValue1!=null,"该商品暂无此属性");
        Assert.state(propValue2!=null,"该商品暂无此属性");
        Assert.state(propValue1.getPropId()!=propValue2.getPropId(),"同种属性值不能相同");
        String value1 = propValue1.getPropValue();//得到第一个属性值
        String value2 = propValue2.getPropValue();
        String brand = spu.getBrand();
        String spuName = spu.getSpuName();
        StringBuilder strbuilder = new StringBuilder();
        strbuilder.append(spuName);
        strbuilder.append("-");
        strbuilder.append(brand);
        strbuilder.append("-");
        strbuilder.append(value1);
        strbuilder.append("-");
        strbuilder.append(value2);
        sku.setSkuName(strbuilder.toString());//设置sku名字
        List<Sku> skus = skuMapper.selectList(null);
        for (Sku sku1 : skus) {
            //判断sku是否重复
            if(sku1.getSkuName().equals(strbuilder.toString())){
                throw new MallException(CarlgoodsResultCode.DATA_NOT_DOUBLE);
            }
        }
        sku.setSkuStatus(ConstData.SKU_STATE_UP);
        sku.setSkuSales(2);
        sku.setDiscount(1.0);
        skuMapper.insert(sku);
        return Result.success();
    }

    @Override
    public Result modifySku(ModifySkuParam param) {
        Sku sku1 = skuMapper.selectById(param.getSkuId());
        Assert.state(sku1!=null,"不存在该商品");
        double before = sku1.getDiscount();
        if(param.getDiscount()==0){
            param.setDiscount(before);
        }
        Sku sku = BeanUtil.toBean(param, Sku.class);
if(sku.getSkuStock()!=null) {
    if (sku1.getSkuStock() < sku.getSkuStock()) {
        throw new MallException(CarlgoodsResultCode.SKU_NOT_STOCK);
    }
    sku.setSkuStock(sku1.getSkuStock() - sku.getSkuStock());
}
        skuService.saveOrUpdate(sku);

        return Result.success();
    }

    @Override
    public Result<String> skuUploadImage(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        String fileName = UUID.randomUUID().toString();
        String url = ossUtil.uploadFile(inputStream, fileName + "." + suffix, "gs-book");
        return Result.success(url) ;
    }

    @Override
    public Result cahngeSkuStock(Long skuId, Integer skuStock) {
        if(skuStock<0){
            throw new MallException(CarlgoodsResultCode.STORE_NOT_EXIST);
        }
        Sku sku = skuMapper.selectById(skuId);
        Assert.state(sku!=null,"该商品不存在");
        sku.setSkuStock(skuStock);
        skuMapper.updateById(sku);
        return Result.success();
    }
}
